AutoCloseable and Flushable
AutoCloseable is an interface in Java that allows a resource to be automatically closed after it has been used. It is especially useful with try-with-resources.
try(FileReader reader = new FileReader("person.txt")){
//use reader
}
Java automatically calls: reader.close(); when the try block finishes.
import java.io.FileReader;
import java.io.IOException;
public class AutoCloseExample {
public static void main(String[] args) {
try (FileReader reader = new FileReader("student.txt")) {
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
There is no explicit: reader.close();
Without try-with-resources:
try{
FileReader reader = new FileReader("person.txt");
}finally{
reader.close();
}
try (FileReader reader = new FileReader("student.txt")) {
// read file
}
Closeable is an interface in java.io
It represents an object that can be closed.
FileInputStream
FileOutputStream
FileReader
FileWriter
BufferedReader
BufferedWriter
implement Closeable directly or through their inheritance hierarchy.
The important method is:
void close() throws IOException
import java.io.*;
public class CloseableExample {
public static void main(String[] args) {
try (FileReader reader = new FileReader("student.txt")) {
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
The FileReader is automatically closed because it implements Closeable, which
extends AutoCloseable.
Actually, the relationship is
public interface Closeable extends AutoCloseable
Therefore: Every Closeable is an AutoCloseable.
But not every AutoCloseable is necessarily a Closeable.
The Flushable interface is used when data is temporarily stored in a buffer. It contains:
void flush() throws IOException
Suppose we write: writer.write("more than 8k meters");
The data may initially be stored in memory (buffer) rather than immediately written to the physical file.
When we call: writer.flush();
Java tells the stream:
Send all buffered data to its destination now.
import java.io.*;
public class FlushExample {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("data.txt")) {
writer.write("Hello Java");
writer.flush();
System.out.println("Data flushed.");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Therefore, after: writer.close(); we cannot continue using the writer.